const user = require("../databases/user");
const jwt = require("jsonwebtoken");
const md5 = require("md5");

module.exports = async (req, res, next)=>{
  const {username, password} = req.body;

  if(!password){
    res.send({
      code:3,
      msg:"缺少关键参数：uId"
    })
    return;
  }

  const data = await user.find({username}, {_id:0, __v:0});
  if(data.length > 0){
    if(data[0].password === md5(password)){

      // 获取cookie：req.cookies.xxx
      // 存储cookie：res.cookie(key, val)
      // 使用cookie技术存储登录成功后的状态
      // res.cookie("uId", data[0].uId);
      // res.cookie("power", data[0].power);
      // res.cookie("isLogin", 1);

      // 获取session：req.session.xxx
      // 存储session：req.session.xxx = xxx
      // 使用session技术存储登录成功后的状态
      // req.session.uId = data[0].uId;
      // req.session.power = data[0].power;
      // req.session.isLogin = true;

      // 生成token字符
      const token = jwt.sign({
        uId: data[0].uId,
        power: data[0].power
      }, "千锋H5", {
        expiresIn: 60 * 30
      })

      res.send({
        code:1,
        msg:"登录成功",
        data: data[0],
        // 将token响应给前端
        token
      })
    }else{
      res.send({
        code:2,
        msg:"密码不对"
      })
    }
  }else{
    res.send({
      code:0,
      msg:"用户名不存在"
    })
  }
}
